import { useEffect, useState, useRef } from 'react';
import { Grid } from 'react-vant';

import SvgIcon from '@/components/SvgIcon/index';
import { debounce } from '@/utils/utils';
import { staticModeList, deviceId } from '@/utils/staticData';
import useStore from '@/store/index';
import './index.less';

interface ModeProps {
  onModeChange: (id: number) => void;
}

export default function Mode({ onModeChange }: ModeProps) {
  const Hejia = (window as any).Hejia;
  const { stopLoop, info, setIsOperating, updateLastOperationTime, scheduleLoopStart } = useStore();

  const { mode, isOnline, state: status, fault, booking } = info;
  const [selectedItemId, setSelectedItemId] = useState<number>(mode);
  const timeoutId = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (!useStore.getState().isOperating) {
      setSelectedItemId(mode);
    }
  }, [mode]);

  const handleModeClick = (id: number): void => {
    if (booking > 0 && [1, 3, 4, 9].includes(id)) return
    if (id === selectedItemId) return;

    setIsOperating(true);
    updateLastOperationTime();

    stopLoop();

    setSelectedItemId(id);
    onModeChange(id);

    clearTimeout(timeoutId.current as NodeJS.Timeout);

    debounce(() => {
      Hejia.setControlParam(
        {
          // deviceId,
          parameters: {
            param: [
              {
                name: 'mode',
                content: id
              }
            ]
          }
        },
        function () {

          setIsOperating(false);
          scheduleLoopStart();
          console.log('success');
        },
        function (msg: string, obj: any) {
          setIsOperating(false);
          setSelectedItemId(mode);
          scheduleLoopStart()
          console.log(msg + obj.resultCode + obj.resultCodeMessage);
        }
      );
    }, 300)();
  };
  const isDisabled = !isOnline || fault > 0 || [1, 2, 3].includes(status);
  return (
    <div className="mode">
      <div
        className={isDisabled ? 'offline-title' : 'title'}
      >
        模式
      </div>
      <div className="mask-wapper">
        {isDisabled && <div className="mask" />}

        <Grid columnNum={4} border={false}>
          {staticModeList.map(item => (
            // react传递参数必须是回调函数
            <Grid.Item key={item.id} >
              <div className='item-wrap'>

                <div
                  onClick={() => handleModeClick(item.id)}
                  className={`item ${item.id === selectedItemId ? 'active' : ''} ${booking > 0 && status == 0 && [1, 3, 4, 9].includes(item.id) ? 'disabled' : ''
                    }`}
                >
                  <SvgIcon
                    name={`${item.svg}`}
                    size="48"
                    color={`${booking > 0 && status == 0 && [1, 3, 4, 9].includes(item.id)
                      ? 'var(--disabled-color)'
                      : item.id === selectedItemId
                        ? 'var(--primary-color)'
                        : 'var(--title-color)'
                      }`}
                  />
                  <span
                    style={{
                      color:
                        booking > 0 && status == 0 && [1, 3, 4, 9].includes(item.id)
                          ? 'var(--disabled-color)'
                          : item.id === selectedItemId
                            ? 'var(--primary-color)'
                            : 'var(--title-color)'
                    }}
                  >
                    {item.title}
                  </span>
                </div>
              </div>

            </Grid.Item>
          ))}
        </Grid>
      </div>
    </div>
  );
}
